package ch.ti.kmltomap;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.google.android.gms.maps.GoogleMap;

public class Kml {
	
	public String xml = "";
	public String ns = "";
	public String hint = "";
	
	public List<Feature> features = null;
	
	public Kml(Reader kmlReader){
		features = new ArrayList<Feature>();
		parseKml(kmlReader);
	}
	
	public Kml(File kmlFile){
		features = new ArrayList<Feature>();
		FileReader reader = null;
		try{
			reader = new FileReader(kmlFile);
			this.parseKml(reader);
		}catch (Exception e) {
			System.err.println("Cannot read kml file");
		}finally{
			try{
				reader.close();
			}catch (Exception e) {
			}
		}
	}
	
	public Kml(String kml){
		features = new ArrayList<Feature>();
		this.xml = kml;
		StringReader sr = new StringReader(kml);
		this.parseKml(sr);
	}

	private void parseKml(Reader kml){
		try{
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			//factory.setNamespaceAware(true);
			XmlPullParser xpp = factory.newPullParser();
	        xpp.setInput(kml);
	        int eventType = xpp.getEventType();
	        while (eventType != XmlPullParser.END_DOCUMENT) {
	        	if(eventType == XmlPullParser.START_TAG){
	        		
	        		if(xpp.getName().equals("kml")){
	        			this.ns = xpp.getNamespace();
	        			try{
	        				this.hint = xpp.getAttributeValue(this.ns, "hint");
	        			}catch (Exception e) {
						}
	        		}
	        		else if(xpp.getName().equals("Folder")){
	        			Folder folder = new Folder(xpp);
	        			this.features.add(folder);
	        		}
	        		else if(xpp.getName().equals("Placemark")){
        				Placemark placeMark = new Placemark(xpp);
	        			this.features.add(placeMark);
	        		}
	        	}
	        	if(eventType == XmlPullParser.END_TAG){
	        		
	        	}
	        	eventType = xpp.next();
	        }
		}catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public void draw(GoogleMap map){
		for (Feature feature : features) {
			feature.draw(map);
		}
	}
	
}
